package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicProductBomDO;
import com.cssy.xxkj.basic.entity.BasicProductBomMaterialsDO;
import com.cssy.xxkj.basic.service.IBasicMaterialsBomService;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.Constants;
import com.cssy.xxkj.logic.entity.LogicProductionGetDO;
import com.cssy.xxkj.logic.entity.LogicProductionGetItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionGetService;
import com.cssy.xxkj.logic.service.ILogicProductionPlanService;
import com.cssy.xxkj.logic.service.ILogicWarehouseInventoryService;
import com.cssy.yd.logic.util.MathUtil;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.OutJsonGrid;
/**
 * 生产领料控制器
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/proget")
public class ProductionGetController extends BaseController<LogicProductionGetDO> {
	
	private static final Logger logger = Logger.getLogger(ProductionGetController.class);

	private static final String MANAGER = "/xxkj/logic/productionget/ProGetManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/productionget/ProGetOperation";// 添加、修改、显示页面

	@Resource(name = "logicProductionGetService")
	private ILogicProductionGetService logicProductionGetService;
	//生产计划Service
	@Resource(name = "logicProductionPlanService")
	private ILogicProductionPlanService logicProductionPlanService;
	
	@Resource(name = "logicWarehouseInventoryService")
	private ILogicWarehouseInventoryService logicWarehouseInventoryService;
	
	@Resource(name="basicMaterialsBomService")
	private IBasicMaterialsBomService basicMaterialsBomService;
	//主数据公用集合Service
	@Resource(name="basicUtilService")
	private IBasicUtilService basicUtilService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;

	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs.setOrderBy("bizCreatorDate desc");
		SearchResult result = logicProductionGetService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("viewflag", "add");
			model.addAttribute("xx", 1);//标示能不能修改内容
		}else{
			LogicProductionGetDO proget = logicProductionGetService.findListById(id);
			model.addAttribute("proget", proget);
			if (proget.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_ONE)||proget.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_SIX)){
				model.addAttribute("xx", 1);//标示能不能修改内容
				model.addAttribute("viewflag", "tijiao");
			}else {
				model.addAttribute("xx", 2);//标示能不能修改内容
			}
			if (proget.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_FIVE)){
				model.addAttribute("viewflag", "tongguo");
			}
			if (proget.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_THREE)){
				model.addAttribute("viewflag", "shenpi");
			}
		}
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionGetDO prodispat = logicProductionGetService.findListById(id);
			List<LogicProductionGetItemDO> soitem = logicProductionGetService.findGetItemList(prodispat.getId());
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicProductionGetDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("itemdata");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicProductionGetService.dispatSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicProductionGetDO ld = logicProductionGetService.findListById(field);
				logicProductionGetService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping("/gridBomitems")
	public void gridBomitems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		String whcode = request.getParameter("whcode");
		if(StringUtils.isNotBlank(id)){
			List<LogicProductionGetItemDO> list = new ArrayList<LogicProductionGetItemDO>();
			LogicProductionPlanDO proplan = logicProductionPlanService.findListById(id);
			List<LogicProductionPlanItemDO> proplanitem = logicProductionPlanService.findPlanItemList(proplan.getId());
			if(proplanitem!=null&&!proplanitem.isEmpty()&&proplanitem.size()>0){
				for(int i=0;i<proplanitem.size();i++){
					SearchConditions scs = new SearchConditions();
					scs.setRemovedProperty("removed");
					scs.addCondition("zd008MaterialsId", proplanitem.get(i).getZd006MaterialsId(),SearchCondition.OP_EQUAL);
					SearchResult result = basicMaterialsBomService.findListByExample(scs);
					List<BasicProductBomDO> bomlist = result.getResults();
					if(bomlist!=null&&!bomlist.isEmpty()&&bomlist.size()>0){
						BasicProductBomMaterialsDO bdo = new BasicProductBomMaterialsDO();
						bdo.setZd001BomId(bomlist.get(0).getId());
						List<BasicProductBomMaterialsDO> bommaterlist = basicMaterialsBomService.materList(bdo).getResults();
					    if(bommaterlist!=null&&!bommaterlist.isEmpty()&&bommaterlist.size()>0){
					    	list.addAll(this.bomConvert(bommaterlist, proplanitem.get(i),proplan.getZd001FormCode(),whcode));
					    }
					}
				}
			}
			OutJsonGrid out = new OutJsonGrid(list);
			out.printJSon(response);
		}
	}
	
	/**
	 * 转化BOM到生产领料
	 * @param bommaterlist
	 * @param logicProductionPlanItemDO
	 * @return
	 * @throws Exception
	 */
	private  List<LogicProductionGetItemDO>  bomConvert(List<BasicProductBomMaterialsDO> bommaterlist,LogicProductionPlanItemDO logicProductionPlanItemDO,String plan,String whcode)throws Exception{
		List<LogicProductionGetItemDO> list = new ArrayList<LogicProductionGetItemDO>();
		List<LogicProductionGetItemDO> ylist =this.listItem(plan);
		for(int i=0;i<bommaterlist.size();i++){
			LogicProductionGetItemDO proget = new LogicProductionGetItemDO();
			proget.setZd022ProCode(logicProductionPlanItemDO.getZd007MaterialsCode());
			proget.setZd023ProName(logicProductionPlanItemDO.getZd008MaterialsName());
			proget.setZd002MaterialsId(bommaterlist.get(i).getZd003MaterialsId());
			proget.setZd002MaterialsCode(bommaterlist.get(i).getBasicMaterialsDO().getZd001Code());
			proget.setZd002MaterialsName(bommaterlist.get(i).getBasicMaterialsDO().getZd002Name());
			proget.setZd003MaterialsSpec(bommaterlist.get(i).getBasicMaterialsDO().getZd003Spec());
			proget.setZd004MaterialsModel(bommaterlist.get(i).getBasicMaterialsDO().getZd004Model());
			proget.setZd006Unit(bommaterlist.get(i).getBasicMaterialsDO().getZd007Unit());
			proget.setZd014MaterialsDescription(bommaterlist.get(i).getBasicMaterialsDO().getZd006Description());
			proget.setZd015MaterialsSize(bommaterlist.get(i).getBasicMaterialsDO().getZd026Size());
			proget.setZd016MaterialsColor(bommaterlist.get(i).getBasicMaterialsDO().getZd033Color());
			proget.setZd017MaterialsQuality(bommaterlist.get(i).getBasicMaterialsDO().getZd034Quality());
			proget.setZd018PlanQuantity(logicProductionPlanItemDO.getZd013Quantity());
			proget.setZd019BomQuantity(bommaterlist.get(i).getZd005Dosage());
			proget.setZd020WareGetQuantity(this.getProductionQuantity(ylist, bommaterlist.get(i).getZd003MaterialsId()));
			proget.setZd021BomId(bommaterlist.get(i).getZd001BomId());
			proget.setZd024WhQuanlity(logicWarehouseInventoryService.getStorageQuaitity(bommaterlist.get(i).getBasicMaterialsDO().getZd001Code(), whcode, null, null, Constants.SYS_DEFAULT_BATCH));
			if(proget.getZd020WareGetQuantity().compareTo(new BigDecimal(0.0))==1){
				BigDecimal bg =MathUtil.mathUtil.subtract(MathUtil.mathUtil.multiply(bommaterlist.get(i).getZd005Dosage(), logicProductionPlanItemDO.getZd013Quantity()), proget.getZd020WareGetQuantity());
				proget.setZd007Quantity(bg);
			 }else{
				proget.setZd007Quantity(MathUtil.mathUtil.multiply(bommaterlist.get(i).getZd005Dosage(), logicProductionPlanItemDO.getZd013Quantity()));
			}
			list.add(proget);
		}
		return list;
	}
	
	/**
	 * 查询当前生产计划单已领料的数量
	 */
	private List<LogicProductionGetItemDO> listItem(String plan)
			throws Exception {
		List<LogicProductionGetItemDO> list = new ArrayList<LogicProductionGetItemDO>();
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		scs.addCondition("zd002OriCode", plan, SearchCondition.OP_EQUAL);
		scs.addCondition("zd011BillStatus", BillStatusUtil.PROGET_STATUS_FIVE, SearchCondition.OP_EQUAL);
		List<LogicProductionGetDO> result = logicProductionGetService.findListByExample(scs).getResults();
		if(result!=null&&!result.isEmpty()&&result.size()>0){
			for(int i=0;i<result.size();i++){
				List<LogicProductionGetItemDO> dispatItem = logicProductionGetService.findGetItemList(result.get(i).getId());
				list.addAll(dispatItem);
			}
		}
		return list;
	}
	
	private BigDecimal getProductionQuantity(List<LogicProductionGetItemDO> list,String proess){
		BigDecimal big = new BigDecimal(0.0);
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			for(int i=0;i<list.size();i++){
				if(list.get(i).getZd002MaterialsId().equals(proess)){
					big=MathUtil.mathUtil.addtract(big, list.get(i).getZd007Quantity());
				}
			}
		}
		return big;
	}
}
